package com.hua.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.mapper.QuestionMapper;
import com.hua.pojo.Question;
import com.hua.pojo.QuestionCategory;
import com.hua.pojo.User;
import com.hua.service.QuestionCategoryService;
import com.hua.service.QuestionService;
import com.hua.service.UserService;
import com.hua.utils.HuaUtil;
import com.hua.vo.ArticleData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author ONE-X
 * @date 2020/11/10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

	static Logger logger = LoggerFactory.getLogger("QuestionServiceImpl");

	@Autowired
	private QuestionService questionService;

	@Autowired
	private QuestionMapper questionMapper;

	@Autowired
	private UserService userService;

	@Autowired
	private QuestionCategoryService questionCategoryService;

	@Override
	public Integer findQuestionByAuthorCount(String authorID) {
		return questionService.count(new QueryWrapper<Question>().eq("author_id", authorID));
	}

	@Override
	public IPage findQuestionPage(IPage<Question> iPage, String s,String uid) {
		QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
		if (!(s == null || s.equals(""))) {
			questionQueryWrapper.eq("category_name", s);
		}
		if (!(uid == null || uid.equals(""))) {
			questionQueryWrapper.eq("author_id", uid);
		}
		questionQueryWrapper.orderByDesc("gmt_create");
		iPage = questionMapper.selectPage(iPage, questionQueryWrapper);
		return iPage;
	}

	@Override
	public void saveQuestion(ArticleData articleData) {
		// 查看用户
		User uid = userService.getOne(new QueryWrapper<User>().eq("uid", HuaUtil.returnAuthentication()));
		if (uid == null) {
			logger.error("添加问题时 无法查看到添加的用户");
			throw new NullPointerException();
		}
		// 查看问题分类
		QuestionCategory category = questionCategoryService.getOne(new QueryWrapper<QuestionCategory>().eq("category", articleData.getCategory()));
		if (category == null) {
			logger.error("添加问题时 无法查看到问题的分类");
			throw new NullPointerException();
		}
		Question question =
				new Question(
						0,
						HuaUtil.getUuid(),
						articleData.getTitle(),
						articleData.getText(),
						0, 0, 0,
						uid.getUid(),
						uid.getUsername(),
						uid.getAvatar(),
						category.getId(),
						category.getCategory(),
						new Date(),
						new Date());
		questionService.save(question);

	}

	@Override
	public void saveStatus(String qid) {
		questionMapper.saveStatus(qid);
	}


}
